package com.dcivision.upload.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.form.bean.FormFileAttachment;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.Utility;
import com.dcivision.workflow.bean.WorkflowProgressAttachment;

public class MultipleFileUploadUtil {

  public static final String REVISION = "$Revision: 1.8.2.2 $";
  
  private static final Log log = LogFactory.getLog(MultipleFileUploadUtil.class);
  
  public static final String STORAGE_ROOT = SystemParameterFactory.getSystemParameter(SystemParameterConstant.WORKFLOW_ATTACHMENT_PHYSICAL_PATH);
  
  private SessionContainer sessionCon = null;
  
  public MultipleFileUploadUtil(SessionContainer sessionCon) {
    this.sessionCon = sessionCon;
  }
  
  public static String getFileName(String fullPath) {
    String fileName = null;
    if (fullPath.lastIndexOf("/") != -1 || fullPath.lastIndexOf("\\") != -1) {
      if (fullPath.lastIndexOf("\\") != -1) {
          fileName = fullPath.substring(fullPath.lastIndexOf("\\") + 1, fullPath.length());
      }
      else {
          fileName = fullPath.substring(fullPath.lastIndexOf("/") + 1, fullPath.length());
      }
    }
    else {
      fileName = fullPath;
    }
    return fileName;
  }
  
  
  //* convert the form hidden value to a List view for better presentation
  public static List getFileListFromFormValue(String formValue) throws ApplicationException {
    List resultList = new ArrayList();
    int count = 0;
    try {
      if (!Utility.isEmpty(formValue)) {
        StringTokenizer tokenizer = new StringTokenizer(formValue, "|");
        if (tokenizer.hasMoreTokens()) {
          try{
            count = Integer.parseInt(tokenizer.nextToken());
          }catch(Exception ex){}
        }
        
        //get the list of converted name and original file name
        while(tokenizer.hasMoreTokens()) {
          String[] arrName = new String[2];
          int colonPos = -1;
          
          String token = tokenizer.nextToken();
          // first element of array is the original file name
          // second element of the array is the converted file name
          if (!Utility.isEmpty(token) && (colonPos=token.indexOf(":"))!=-1 ) {
            arrName[0] = token.substring(0, colonPos);
            arrName[1] = token.substring(colonPos+1);
            
            resultList.add(arrName);
          }
        }
        
        //checking
        if (count == resultList.size()) {
          log.debug("--getFileListFromFormValue EQUALS --");
        } else {
          log.debug("--getFileListFromFormValue * NOT * EQUALS --");
        }
      }
      return resultList;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(e.toString(), e);
    }
  }
  
  //* convert the form hidden data to a list of WorkflowProgressAttachment Object so that can be used later
  public List getWorkflowAttachmentList(String formValue, String flowType) throws ApplicationException {
    List resultList = new ArrayList();
    WorkflowProgressAttachment attachment = null;
    InputStream inputStream = null;
    String sessionID = sessionCon.getSessionID();
    try {
      List fileNameList = getFileListFromFormValue(formValue);
      
      for (int i=0; i<fileNameList.size(); i++) {
        String[] arrName = (String[]) fileNameList.get(i);
        String originalName = arrName[0];
        String convertedName = arrName[1];
        String fullPath = STORAGE_ROOT + "/" + sessionID + "/" + convertedName;
        
        if (Utility.isEmpty(sessionID)) {
          fullPath = STORAGE_ROOT + "/" + convertedName;
        }
        
        File tmpFile = new File(fullPath);
        // make sure it is still exist
        if (tmpFile.exists()) {
          inputStream = new FileInputStream(tmpFile);
          
          attachment = new WorkflowProgressAttachment();
          attachment.setAttachmentName(originalName);
          attachment.setExternalID(convertedName);
          attachment.setFlowType(flowType);
          attachment.setDataStream(inputStream);
          attachment.setContentSize(new Integer(""+tmpFile.length()));
          attachment.setAttachmentType(WorkflowProgressAttachment.ATTACHED_SINGLE_FILE);
          
          resultList.add(attachment);
        } else {
        }
      }
      
      return resultList;
    } catch (ApplicationException appEx) {
      log.error("application exception in getWorkflowAttachmentList: ", appEx);
      throw appEx;
    } catch (IOException ioe) {
      log.error(ioe, ioe);
      throw new ApplicationException(ioe.toString(), ioe);
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(e.toString(), e);
    }
  }
  
//* convert the form hidden data to a list of WorkflowProgressAttachment Object so that can be used later
  public List getFormFileAttachmentList(String formValue, String flowType) throws ApplicationException {
    List resultList = new ArrayList();
    FormFileAttachment attachment = null;
    InputStream inputStream = null;
    String sessionID = sessionCon.getSessionID();
    try {
      List fileNameList = getFileListFromFormValue(formValue);
      
      for (int i=0; i<fileNameList.size(); i++) {
        String[] arrName = (String[]) fileNameList.get(i);
        String originalName = arrName[0];
        String convertedName = arrName[1];
        String fullPath = STORAGE_ROOT + "/" + sessionID + "/" + convertedName;
        
        File tmpFile = new File(fullPath);
        // make sure it is still exist
        if (tmpFile.exists()) {
          inputStream = new FileInputStream(tmpFile);
          
          attachment = new FormFileAttachment();
          attachment.setAttachmentName(originalName);
          attachment.setExternalID(convertedName);
          attachment.setFlowType(flowType);
          attachment.setDataStream(inputStream);
          attachment.setContentSize(new Integer(""+tmpFile.length()));
          attachment.setAttachmentType(WorkflowProgressAttachment.ATTACHED_SINGLE_FILE);
          
          resultList.add(attachment);
        } else {
          log.debug("attachment "+originalName+" is missing");
        }
      }
      
      return resultList;
    } catch (ApplicationException appEx) {
      log.error("application exception in getWorkflowAttachmentList: ", appEx);
      throw appEx;
    } catch (IOException ioe) {
      log.error(ioe, ioe);
      throw new ApplicationException(ioe.toString(), ioe);
    } catch (Exception e) {
      log.error("exception in getWorkflowAttachmentList: ", e);
      throw new ApplicationException(e.toString(), e);
    }
  }
}